/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.rbac.service.role.impl;

import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.je.common.base.DynaBean;
import com.je.common.base.service.MetaService;
import com.je.common.base.util.DateUtils;
import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.rbac.rpc.AccountRpcService;
import com.je.rbac.service.role.RbacAccountRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class RbacAccountRoleServiceImpl implements RbacAccountRoleService {

    @Autowired
    private AccountRpcService accountRpcService;
    @Autowired
    private MetaService metaService;


    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void updateAccountRoles(String accountId, String originalRoleIds, String currentRoleIds, String deptId, String deptName, String deptUserCode) {
        String deletedRoleIds = accountRpcService.getAddedOrDeleteIds("removed", originalRoleIds, currentRoleIds);
        String addedRoleIds = accountRpcService.getAddedOrDeleteIds("added", originalRoleIds, currentRoleIds);
        if (!Strings.isNullOrEmpty(addedRoleIds)) {
            addAccountRoles(accountId, deptId, deptName, addedRoleIds, deptUserCode);
        }
        if (!Strings.isNullOrEmpty(deletedRoleIds)) {
            removeUserRoles(accountId, deletedRoleIds);
        }
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void addAccountRoles(String accountId, String deptId, String deptName, String roleIds, String deptUserCode) {
        List<String> roleIdList = Splitter.on(",").splitToList(roleIds);
        List<DynaBean> roleList = metaService.select("JE_RBAC_ROLE", ConditionsWrapper.builder().in("JE_RBAC_ROLE_ID", roleIdList));

        List<DynaBean> accountDeptRoleModelList = new ArrayList<>();
        DynaBean accountDeptRoleTempBean;
        for (DynaBean roleBean : roleList) {
            int sysOrderIndex = -1;
            List<Map<String, Object>> userOrderList = metaService.selectSql("SELECT MAX(SY_ORDERINDEX) AS MAX_COUNT FROM JE_RBAC_ACCOUNTROLE WHERE ACCOUNTROLE_ROLE_ID={0}", roleBean.getStr("JE_RBAC_ROLE_ID"));
            if (userOrderList.size() > 0) {
                sysOrderIndex = Integer.valueOf(userOrderList.get(0).get("MAX_COUNT").toString());
            }
            accountDeptRoleTempBean = new DynaBean("JE_RBAC_ACCOUNTROLE", false);
            accountDeptRoleTempBean.set("ACCOUNTROLE_ACCOUNT_ID", accountId);
            accountDeptRoleTempBean.set("ACCOUNTROLE_DEPT_ID", deptId);
            accountDeptRoleTempBean.set("ACCOUNTROLE_DEPT_NAME", deptName);
            accountDeptRoleTempBean.set("ACCOUNTROLE_MAIN_CODE", deptUserCode);
            accountDeptRoleTempBean.set("ACCOUNTROLE_ROLE_ID", roleBean.getStr("JE_RBAC_ROLE_ID"));
            accountDeptRoleTempBean.set("ACCOUNTROLE_ROLE_NAME", roleBean.getStr("ROLE_NAME"));
            accountDeptRoleTempBean.set("SY_ORDERINDEX", sysOrderIndex);
            accountDeptRoleTempBean.set("SY_CREATETIME", DateUtils.formatDateTime(new Date()));
            accountDeptRoleModelList.add(accountDeptRoleTempBean);
        }

        List<String> accountIdList = new ArrayList<>();
        for (DynaBean eachBean : accountDeptRoleModelList) {
            accountIdList.add(eachBean.getStr("ACCOUNTROLE_ACCOUNT_ID"));
        }

        List<DynaBean> existsAccountDeptRoleList = metaService.select("JE_RBAC_ACCOUNTROLE", ConditionsWrapper.builder()
                .in("ACCOUNTROLE_ACCOUNT_ID", accountIdList));
        List<DynaBean> needRemovedBeanList = new ArrayList<>();
        for (DynaBean eachExistsBean : existsAccountDeptRoleList) {
            for (DynaBean eachNeedInsertBean : accountDeptRoleModelList) {
                if (eachExistsBean.getStr("ACCOUNTROLE_ACCOUNT_ID").equals(eachNeedInsertBean.getStr("ACCOUNTROLE_ACCOUNT_ID"))
                        && eachExistsBean.getStr("ACCOUNTROLE_DEPT_ID").equals(eachNeedInsertBean.getStr("ACCOUNTROLE_DEPT_ID"))
                        && eachExistsBean.getStr("ACCOUNTROLE_ROLE_ID").equals(eachNeedInsertBean.getStr("ACCOUNTROLE_ROLE_ID"))) {
                    needRemovedBeanList.add(eachNeedInsertBean);
                }
            }
        }
        accountDeptRoleModelList.removeAll(needRemovedBeanList);
        metaService.insertBatch("JE_RBAC_ACCOUNTROLE", accountDeptRoleModelList);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public long removeAccountRoles(String accountId, String deptId, String deptName, String roleIds) {
        List<String> roleIdList = Splitter.on(",").splitToList(roleIds);
        return metaService.delete("JE_RBAC_ACCOUNTROLE", ConditionsWrapper.builder()
                .eq("ACCOUNTROLE_ACCOUNT_ID", accountId).eq("ACCOUNTROLE_DEPT_ID", deptId)
                .in("ACCOUNTROLE_ROLE_ID", roleIdList));
    }

    /***
     * 员工管理-当删除员工角色时，将该角色下所有账号部门关系都删除
     * @param accountId
     * @param roleIds
     * @return
     */
    @Transactional(rollbackFor = RuntimeException.class)
    public long removeUserRoles(String accountId, String roleIds) {
        List<String> roleIdList = Splitter.on(",").splitToList(roleIds);
        return metaService.delete("JE_RBAC_ACCOUNTROLE", ConditionsWrapper.builder()
                .eq("ACCOUNTROLE_ACCOUNT_ID", accountId)
                .in("ACCOUNTROLE_ROLE_ID", roleIdList));
    }

}
